import React from 'react';
import axios from 'axios';
import './3.3-ComponentDidMount.css';

export const DISPLAY_USER_ID = 1


class Demo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      userList: [],
    };
  }

  getUserPromise = (idList) =>{
    return idList.map((id => {
        return axios.get(`https://xiaozhu.run/api/user/${id}`)
    }))
  }

  async componentDidMount() {

    const resList = await Promise.all([
      axios.get(`https://xiaozhu.run/api/user/${DISPLAY_USER_ID}`),
      ...this.getUserPromise([9527,9528,9529]),
    ])

    // const res = await axios.get('https://xiaozhu.run/api/user/1')
    // console.log('ID 1',res)
    // const resList =  await Promise.all(this.getUserPromise([9527,9528,9529])
    
    // console.log('res',resList);
    const userList = resList.slice(1).map((user) => {
      return user.data.data
    })
    console.log('userList',userList);
    this.setState({userList:userList})
    //axios.get('https://xiaozhu.run/api/user/') 回调函数发异步请求 会造成回调很深 可维护性低 可用ES6语法塘
      
    

    // 可以做1：获取 dom
    // console.log(this.myRef.current);
    // 可以做2：ajax
    // axios.get('https://xiaozhu.run/api/user/9527').then((res) => {
    //   this.setState({
    //     username1: res.data.data.username,
    //     email1 : res.data.data.email,
    //   });
    // });

    // axios.get('https://xiaozhu.run/api/user/9528').then((res) => {
    //   this.setState({
    //     username2: res.data.data.username,
    //     email2 : res.data.data.email,
    //   });
    // });
  }

  render() {

    return (
      <div className="user-list">
        {this.state.userList.map((user,index) => {
          if(user.id === DISPLAY_USER_ID){
            return null;
          }else{
            return (
              <React.Fragment key={user.id}>
                <p>Id : {user.id}</p>
                <p>UserName: {user.username}</p>
                <p>Email: {user.email}</p>
                {/* {方式1：} */}
                {/* {this.state.userList.length -1 !== index && <hr/>} */}
                <hr />
              </React.Fragment>
            )
          } 
        })}
      </div>
    )
  }
}

export default Demo;
